package com.yantong.aspect;

import com.yantong.result.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author: juzi
 * @date: 2021/12/3
 * @time: 14:59
 */
@RestControllerAdvice
public class BadRequestExceptionHandler {


    private static final Logger logger = LoggerFactory.getLogger(BadRequestExceptionHandler.class);

    /**
     *  校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo validationBodyException(MethodArgumentNotValidException exception){
        ResultVo resultVo =  ResultVo.error();
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {

            List<ObjectError> errors = result.getAllErrors();

            errors.forEach(p ->{

                FieldError fieldError = (FieldError) p;
//                logger.error("Data check failure : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
//                        "},errorMessage{"+fieldError.getDefaultMessage()+"}");
                resultVo.put(fieldError.getField(),fieldError.getDefaultMessage());

            });

        }
        return resultVo;
    }

    /**
     * 参数类型转换错误
     *
     * @param exception 错误
     * @return 错误信息
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public ResultVo parameterTypeException(HttpMessageConversionException exception){

        logger.error(exception.getCause().getLocalizedMessage());
        return ResultVo.error("类型转换错误");

    }

}
